package cr

import (
	"fmt"
	"github.com/go-playground/locales/en"
	zhongwen "github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	en2 "github.com/go-playground/validator/v10/translations/en"
	zh2 "github.com/go-playground/validator/v10/translations/zh"
	"learn/app/request"
	"learn/config"
	"reflect"
	"strings"
)

func isEmail(fl validator.FieldLevel) bool {
	email := fl.Field().String()
	// 这里简单地检查@符号，实际情况下应该使用更复杂的正则表达式来验证邮箱格式
	return len(email) > 0 && strings.Contains(email, "@")
}

const (
	RequireLte30   = "requireLte30"    // 必填&长度必须小于等于30的校验，eg:身份证宽松限制，
	Require36      = "require36"       // 必填&长度必须等于36的校验 uuid 数据库主键,
	RequireLte50   = "requireLte50"    // 长度必须等于50的校验,eg:名称
	RequireLte64   = "requireLte64"    // 必填&长度必须等于64的校验，eg:orgCode
	RequireLte100  = "requireLte100"   // 必填&长度必须等于100的校验
	Options01      = "options0_1"      // int类 bool 判断
	Mobile         = "mobile"          // 手机号码（1开头的是一位数字）
	UserMobile     = "userMobile"      // 用户登录手机号码（6-20的字符串）
	Email          = "email"           // 邮箱
	Password       = "password"        // 密码
	VerifyCode4    = "verify_code4"    // 4位验证码
	SliceRequire36 = "slice_require36" // 不为空的UUID切片
	DateTime       = "datetime"        // 日期时间校验 2006-01-02 15:04:05
	Date           = "date"            // 日期时间校验 2006-01-02
	Time           = "time"            // 日期时间校验 15:04:05
	Time_H_S       = "time_H_S"        // 日期时间校验 15:04

	DefStr = "defStr"
	//DateLteWith     = "date_lte_with"     // 日期小于等于另一字段日期
	//DateLtWith      = "date_lt_with"      // 日期小于另一字段日期
	//DateGteWith     = "date_gte_with"     // 日期大于等于另一字段日期
	//DateGtWith      = "date_gt_with"      // 日期大于另一字段日期
	//DatetimeLteWith = "datetime_lte_with" // 日期时间小于等于另一字段日期时间
	//DatetimeLtWith  = "datetime_lt_with"  // 日期时间小于另一字段日期时间
	//DatetimeGteWith = "datetime_gte_with" // 日期时间大于等于另一字段日期时间
	//DatetimeGtWith  = "datetime_gt_with"  // 日期时间大于等于另一字段日期时间
)

// 定义别名，对应多个校验器
var aliasMap = map[string]string{
	Require36:      "required,len=36",
	VerifyCode4:    "len=4",
	RequireLte30:   "required,lte=30",
	RequireLte64:   "required,lte=64",
	RequireLte50:   "required,lte=50",
	RequireLte100:  "required,lte=100",
	Options01:      "oneof=0 1",
	Mobile:         "len=11,numeric,startNumOne",
	UserMobile:     "max=20,min=6",
	Email:          "customEmail",
	Password:       "gte=6,lte=12",
	SliceRequire36: "gt=0,dive,required,len=36",
	DateTime:       "normalDateTime",
	Date:           "normalDate",
	Time:           "normalTime",
	Time_H_S:       "normalTime_H_S",
	DefStr:         "let=255",
}

//	func init() {
//		// 注册自定义验证规则
//
//		//for _, validateFunc := range []func() (string, validate.FuncCtx){customEmail, normalDatetime, normalDate, normalTime, normalTime_H_S, startNumOne, trimString, leftTrimString, rightTrimString, dateLteWith, dateLtWith, dateGteWith, dateGtWith, datetimeLteWith, datetimeLtWith, datetimeGteWith, datetimeGtWith} {
//		//	tag, fn := validateFunc()
//		//	if err := validatorV2.RegisterValidationCtx(tag, fn); err != nil {
//		//		panic("RegisterValidationCtx tag:" + tag + " err:" + err.Error())
//		//	}
//		//}
//
//		for alias, validateStr := range aliasMap {
//			validatorV2.RegisterAlias(alias, validateStr)
//		}
//	}
//

func InitValidate(validatorV2 *validator.Validate) {
	// 注册自定义验证规则
	//for _, validateFunc := range []func() (string, validator.FuncCtx){isEmail} {
	//	tag, fn := validateFunc()
	//	if err := validatorV2.RegisterValidationCtx(tag, fn); err != nil {
	//		panic("RegisterValidationCtx tag:" + tag + " err:" + err.Error())
	//	}
	//}

	err := validatorV2.RegisterValidation("email", isEmail)

	fmt.Print(err)
	for alias, validateStr := range aliasMap {
		validatorV2.RegisterAlias(alias, validateStr)
	}
}

// https://cloud.tencent.com/developer/article/1693818
// https://blog.csdn.net/qq_52510579/article/details/128281060'
// validate:"numeric"
// Field validate:"eqfield=Field2"  =
func InitLang(validate *validator.Validate) ut.Translator {
	zh := zhongwen.New()
	enT := en.New()
	uni := ut.New(zh, zh, enT)

	locale := config.GlobalLanguage
	trans, _ := uni.GetTranslator(locale)

	//RegisterDefaultTranslations
	switch locale {
	case "en":
		if err := en2.RegisterDefaultTranslations(validate, trans); err != nil {
			// todo
		}
	case "zh":
		if err := zh2.RegisterDefaultTranslations(validate, trans); err != nil {
			// todo
		}
	}

	return trans
}

func CustomTagNameFunc(filed reflect.StructField) string {
	label := filed.Tag.Get("label") // 判断label 不存在取json的值
	if len(label) == 0 {
		label = filed.Tag.Get("json") // 判断label 不存在取json的值
	}

	if len(request.LabelName[label][config.GlobalLanguage]) > 0 {
		return request.LabelName[label][config.GlobalLanguage]
	}
	return filed.Name // 多语言的数组
}
